<template>
  <div class="w-full h-full pt-2">
    <!-- <a-select
      v-model:value="mrmCode"
      class="w-[335px]"
      :options="caseTypeOptions"
      :field-names="{ label: 'mrmName', value: 'mrmCode' }"
      placeholder="病历类型"
    /> -->
    <!-- 常规检查 -->
    <div v-if="(mrmCode === 'YKBL2' || mrmCode === 'YKBL3') && store.currentPatient.jzbh">
      <div class="flex justify-between mb-2">
        <BaseTitle :title="'常规检查'" class="!mb-0" />
        <div class="flex justify-end w-1/2">
          <div class="mr-4 mt-1 text-black"><span class="text-gray-400 mr-1">操作员</span>{{ inspectData.ysmc ? inspectData.ysmc : '-' }}</div>
          <div class="mr-4 mt-1 text-black"><span class="text-gray-400 mr-1">操作时间</span>{{ inspectData.jcsj ? inspectData.jcsj : '-' }}</div>
          <img v-if="inspectShow" src="../../../../assets/images/up.png" class="w-6 h-6 mr-2 cursor-pointer" alt="" @click="tranInspect(false)" />
          <img v-else src="../../../../assets/images/down.png" class="w-6 h-6 mr-2 cursor-pointer" alt="" @click="tranInspect(true)" />
        </div>
      </div>
      <InspectionTable v-if="inspectShow" :resource-data="inspectData" :jzbh="store.currentPatient.jzbh" :setbh="setbh" @success="getInspectData" />
    </div>
    <!-- 病历 -->
    <div class="flex justify-between items-center">
      <div class="flex justify-between">
        <BaseTitle :title="'病历信息'" class="!mb-0" />
        <div class="flex items-center">
          <div class="ml-5 mr-2 w-[100px]">客户已签署文书</div>
          <a-switch v-model:checked="formState.signPaperwork" />
        </div>
      </div>
      <div class="overflow-hidden flex-1 flex justify-end mt-1">
        <a-button v-if="getSystemConfig('IS_OUTP_VIEW_MEDICAL_HISTORY_RECORD') === '1' && !isArmy" class="mr-2" @click="onClickRead">调阅病史</a-button>
        <a-button v-if="getSystemConfig('IS_OUTP_INVOKE_MEDICAL_HISTORY_RECORD') === '1' && !isArmy" @click="onClickHistory">调用病史</a-button>
        <a-button type="primary" ghost class="mx-2" @click="templateModalOpen = true">病历模板</a-button>
        <a-button v-if="getSystemConfig('IS_OUTP_PRINT_MEDICAL_RECORD2') === '1'" class="mr-2" @click="onPrintMedical">{{
          mrmCode === 'ZYBL' ? '打印中医病历' : '打印病历单'
        }}</a-button>
        <template v-if="mrmCode === 'YKBL2' || mrmCode === 'YKBL3'">
          <a-button v-if="getSystemConfig('IS_OUTP_PRINT_OPHTHALMIC_MEDICAL_RECORD') === '1' && !isArmy" class="mr-2" @click="onPrintEye">
            打印眼科病历</a-button
          >
        </template>
        <template v-if="mrmCode !== 'YKBL3' && !isArmy">
          <a-button
            v-if="isPrintStatus === '1' && getSystemConfig('IS_OUTP_PRINT_MEDICAL_RECORD_RECEIPT') === '1'"
            :disabled="!formState.isCommit === 1"
            @click="onPrint"
          >
            打印病历小票</a-button
          >
          <a-button
            v-if="isPrintStatus !== '1' && getSystemConfig('IS_OUTP_PRINT_MEDICAL_RECORD') === '1'"
            :disabled="!formState.isCommit === 1"
            @click="onPrint"
          >
            打印病程单</a-button
          >
          <!-- <a-button @click="onPrint"> {{ printTitle }}</a-button> -->
          <a-button v-if="getSystemConfig('IS_OUTP_PRINT_MERGE_MEDICAL_RECORD') === '1'" class="mx-2" @click="onPrintS"> 合并打印</a-button>
        </template>
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
        </div>
      </div>
    </div>
    <a-form class="mt-4" :disabled="!store.currentPatient.jzbh">
      <!-- 西医病历 -->
      <div v-if="mrmCode === 'XYBL'" class="case-table my-2">
        <div v-for="item in WMItems" :key="item.value" class="case-item">
          <template v-if="item.label === '处置'">
            <div class="label flex-col justify-center">
              <div>医嘱</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetDispose(2, false)">获取医嘱</a-button>
            </div>
            <div class="content h-[54px]">
              <a-textarea v-model:value="formState[item.value]" :disabled="formState.isCommit === 1" placeholder="请输入" :rows="4" />
            </div>
          </template>
          <template v-else-if="item.label === '辅助检查'">
            <div class="label flex justify-between items-center" :class="{ large: item.textarea }">
              <div>{{ item.label }}</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetFZCheck()">提取</a-button>
            </div>
            <div class="content h-[54px]">
              <a-textarea v-model:value="formState[item.value]" :disabled="formState.isCommit === 1" placeholder="请输入" :rows="4" />
            </div>
          </template>
          <template v-else>
            <div class="label" :class="{ required: item.label === '初步诊断' }">{{ item.label }}</div>
            <div class="content h-[54px]">
              <SelectTable
                v-if="item.label === '初步诊断'"
                v-model:value="formState[item.value]"
                type="诊断"
                :custom-input="diagnosisCode"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                @clear="onClear"
                @select="onSelect(item.value, item.code, $event)"
                @input-change="onInputChange(item.code)"
              />
              <SelectTable
                v-if="item.label === '其他诊断'"
                v-model:value="formState[item.value]"
                multiple
                type="诊断"
                :auto-mark="false"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                @select="onSelect(item.value, item.code, $event, true)"
                @clear="inputChange(item.value, item.code, $event)"
                @blur="inputChange(item.value, item.code, $event)"
              />
              <SelectTags
                v-else-if="item.label === '主诉'"
                v-model:value="formState[item.value]"
                :disabled="formState.isCommit === 1"
                input-class="pr-64"
                show-setting
                show-new
                multiple
                type="医嘱字典"
                :search-params="{ blcybh: item.label }"
              >
                <template #addonAfter>
                  <div class="textarea-with-data-picker flex items-center">
                    发病日期<a-date-picker
                      v-model:value="formState.onsetDate"
                      class="ml-2"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      @click="handleChildClick"
                    />
                  </div>
                </template>
              </SelectTags>
              <SelectTags
                v-else
                v-model:value="formState[item.value]"
                :disabled="formState.isCommit === 1"
                show-setting
                show-new
                multiple
                type="医嘱字典"
                :search-params="{ blcybh: item.label }"
              />
            </div>
          </template>
        </div>
      </div>
      <!-- 中医 -->
      <div v-else-if="mrmCode === 'ZYBL'" class="case-table my-2">
        <div v-for="item in TCMItems" :key="item.value" class="case-item">
          <div class="label" :class="{ required: item.label === '西医诊断' || item.label === '中医诊断' || item.label === '中医证名' }">{{ item.label }}</div>
          <div class="content h-[54px]">
            <SelectTable
              v-if="item.label === '西医诊断'"
              v-model:value="formState[item.value]"
              type="诊断"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event)"
            />
            <SelectTable
              v-if="item.label === '中医诊断'"
              v-model:value="formState[item.value]"
              type="中医诊断"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event)"
            />
            <SelectTable
              v-if="item.label === '中医证名'"
              v-model:value="formState[item.value]"
              type="中医证名"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event)"
            />
            <SelectTags
              v-else-if="item.label === '主诉'"
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              input-class="pr-64"
              show-setting
              show-new
              multiple
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            >
              <template #addonAfter>
                <div class="textarea-with-data-picker flex items-center">
                  发病日期<a-date-picker
                    v-model:value="formState.onsetDate"
                    class="ml-2"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @click="handleChildClick"
                  />
                </div>
              </template>
            </SelectTags>
            <a-textarea v-else-if="item.textarea" v-model:value="formState[item.value]" placeholder="请输入" :disabled="formState.isCommit === 1" />
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event, true)"
              @clear="inputChange(item.value, item.code, $event)"
              @blur="inputChange(item.value, item.code, $event)"
            />
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              show-setting
              show-new
              multiple
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <!-- 眼科病历一 -->
      <div v-else-if="mrmCode === 'YKBL1'" class="case-table my-2">
        <div v-for="item in EYEItems1" :key="item.value" class="case-item">
          <div class="label h-10" :class="{ required: item.label === '初步诊断', large: item.textarea }">{{ item.label }}</div>
          <div class="content">
            <div v-if="item.label === '初步诊断'" class="flex h-[54px]">
              <SelectTable
                v-model:value="formState[item.value]"
                type="诊断"
                :custom-input="diagnosisCode"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                @clear="onClear"
                @select="onSelect(item.value, item.code, $event)"
                @input-change="onInputChange(item.code)"
              />
              <a-radio-group v-model:value="formState.bcYblb" :disabled="formState.isCommit === 1" class="flex items-center" name="radioGroup">
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
            </div>
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event, true)"
              @clear="inputChange(item.value, item.code, $event)"
              @blur="inputChange(item.value, item.code, $event)"
            />
            <SelectTags
              v-else-if="item.label === '主诉'"
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              :row-val="item.textarea ? 4 : 2"
              input-class="pr-64"
              show-setting
              show-new
              multiple
              :input-or-textarea="false"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            >
              <template #addonAfter>
                <div class="textarea-with-data-picker flex items-center">
                  发病日期<a-date-picker
                    v-model:value="formState.onsetDate"
                    class="ml-2"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @click="handleChildClick"
                  />
                </div>
              </template>
            </SelectTags>
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              show-setting
              show-new
              multiple
              :row-val="item.textarea ? 4 : 2"
              :input-or-textarea="false"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <!-- 眼科病历二 -->
      <div v-else-if="mrmCode === 'YKBL2'" class="case-table my-2">
        <div v-for="item in EYEItems2" :key="item.value" class="case-item">
          <template v-if="item.label === '处理'">
            <div class="label flex justify-between items-center" :class="{ large: item.textarea }">
              <div>处理</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetDispose(1, true)">提取</a-button>
            </div>
          </template>
          <template v-else-if="item.label === '辅助检查'">
            <div class="label flex justify-between items-center" :class="{ large: item.textarea }">
              <div>{{ item.label }}</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetFZCheck()">提取</a-button>
            </div>
          </template>
          <div v-else-if="item.label !== '眼部检查'" class="label h-10" :class="{ required: item.label === '初步诊断', large: item.textarea }">
            {{ item.label }}
          </div>
          <div v-else-if="!isArmy" class="label-eye">
            <div class="eye-border-left">
              <div class="eye-border-left-con">眼部检查</div>
            </div>
            <div class="eye-border-right">
              <div v-for="(cItem, cIndex) in EYEChildItems" :key="cIndex" class="eye-border-right-con h-10">{{ cItem.label }}</div>
            </div>
          </div>
          <div :class="[isArmy && item.label === '眼部检查' ? 'content content-border-none' : 'content']">
            <div v-if="item.label === '初步诊断'" class="flex h-[54px]">
              <SelectTable
                v-model:value="formState[item.value]"
                type="诊断"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                :custom-input="diagnosisCode"
                @clear="onClear"
                @select="onSelect(item.value, item.code, $event)"
                @input-change="onInputChange(item.code)"
              />
              <a-radio-group v-model:value="formState.bcYblb" :disabled="formState.isCommit === 1" class="flex items-center" name="radioGroup">
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
            </div>
            <div v-else-if="item.label === '眼部检查'">
              <div v-if="!isArmy">
                <div v-for="(cItem, cIndex) in EYEChildItems" :key="cIndex" class="eye-wrap h-10">
                  <div v-if="cItem.label === '眼别'" class="flex h-full eye-box justify-center items-center">
                    <div class="eye-box-header-left h-full">右眼（OD）</div>
                    <div class="eye-box-header-right h-full">左眼（OS）</div>
                  </div>
                  <div v-else-if="cItem.key == '备注'" class="eye-box-left h-full w-full">
                    <a-input v-model:value="formData[cItem.memoOD]" :disabled="formState.isCommit === 1" allow-clear placeholder="请输入" />
                  </div>
                  <div v-else class="flex eye-item-box h-full">
                    <!-- 右眼（OD） -->
                    <div v-if="cItem.key == '眼底视盘'" class="eye-box-left h-full w-1/2">
                      <a-input v-model:value="formData[cItem.valueOD]" :disabled="formState.isCommit === 1" allow-clear placeholder="请输入" />
                    </div>
                    <div v-else-if="cItem.key == '其他检查'" class="eye-box-left h-full w-1/2">
                      <SelectOptions
                        v-model:value="formData[cItem.valueOD]"
                        :select-mode="cItem.mode"
                        :type="cItem.key"
                        trigger="focus"
                        allow-clear
                        :auto-mark="false"
                        :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                        @select="onSelectPageTwo(item.value, item.code, $event, true)"
                      />
                    </div>
                    <div v-else class="eye-box-left h-full">
                      <div class="eye-box-left-br h-full w-1/2">
                        <a-input
                          v-if="cItem.key == '晶状体位置'"
                          v-model:value="formData[cItem.valueOD]"
                          :disabled="formState.isCommit === 1"
                          placeholder="请输入"
                          allow-clear
                        />
                        <SelectOptions
                          v-else
                          v-model:value="formData[cItem.valueOD]"
                          :select-mode="cItem.mode"
                          :type="cItem.key"
                          trigger="focus"
                          allow-clear
                          :auto-mark="false"
                          :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                          @select="onSelect(item.value, item.code, $event, false)"
                        />
                      </div>
                      <div v-if="cItem.key == '晶状体'" class="h-0 w-1/2"></div>
                      <div v-else-if="cItem.key == '晶状体位置'" class="h-20 w-1/2 bg-white -mt-[40px] input-bt">
                        <SelectTags
                          v-model:value="formData[cItem.memoOD]"
                          show-setting
                          show-new
                          multiple
                          type="医嘱字典"
                          :search-params="{ blcybh: cItem.searchKey }"
                          :input-or-textarea="true"
                          :disabled="formState.isCommit === 1"
                          allow-clear
                          placeholder="备注"
                        />
                        <!-- <a-input v-model:value="formData[cItem.memoOD]" class="h-full" :disabled="formState.isCommit === 1" allow-clear placeholder="备注" /> -->
                      </div>
                      <div v-else class="h-full w-1/2">
                        <SelectTags
                          v-model:value="formData[cItem.memoOD]"
                          show-setting
                          show-new
                          multiple
                          type="医嘱字典"
                          :search-params="{ blcybh: cItem.searchKey }"
                          :input-or-textarea="true"
                          :disabled="formState.isCommit === 1"
                          allow-clear
                          placeholder="备注"
                        />
                        <!-- <a-input v-model:value="formData[cItem.memoOD]" :disabled="formState.isCommit === 1" allow-clear placeholder="备注" /> -->
                      </div>
                    </div>
                    <!-- 左眼（OS） -->
                    <div v-if="cItem.key == '眼底视盘'" class="eye-box-right h-full">
                      <a-input v-model:value="formData[cItem.valueOS]" :disabled="formState.isCommit === 1" allow-clear placeholder="请输入" />
                    </div>
                    <div v-else-if="cItem.key == '其他检查'" class="eye-box-right h-full">
                      <SelectOptions
                        v-model:value="formData[cItem.valueOS]"
                        :select-mode="cItem.mode"
                        :type="cItem.key"
                        trigger="focus"
                        allow-clear
                        :auto-mark="false"
                        :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                        @select="onSelectPageTwo(item.value, item.code, $event, true)"
                      />
                    </div>
                    <div v-else class="eye-box-right h-full">
                      <div class="eye-box-right-br h-full w-1/2">
                        <a-input
                          v-if="cItem.key == '晶状体位置'"
                          v-model:value="formData[cItem.valueOS]"
                          :disabled="formState.isCommit === 1"
                          allow-clear
                          placeholder="请输入"
                        />
                        <SelectOptions
                          v-else
                          v-model:value="formData[cItem.valueOS]"
                          :select-mode="cItem.mode"
                          :type="cItem.key"
                          trigger="focus"
                          allow-clear
                          :auto-mark="false"
                          :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                          @select="onSelect(item.value, item.code, $event, false)"
                        />
                      </div>
                      <div v-if="cItem.key == '晶状体'" class="h-0 w-1/2"></div>
                      <div v-else-if="cItem.key == '晶状体位置'" class="h-20 w-1/2 bg-white -mt-[40px] input-bt">
                        <SelectTags
                          v-model:value="formData[cItem.memoOS]"
                          show-setting
                          show-new
                          multiple
                          type="医嘱字典"
                          :search-params="{ blcybh: cItem.searchKey }"
                          :input-or-textarea="true"
                          :disabled="formState.isCommit === 1"
                          allow-clear
                          placeholder="备注"
                        />
                      </div>
                      <div v-else class="h-full w-1/2">
                        <SelectTags
                          v-model:value="formData[cItem.memoOS]"
                          show-setting
                          show-new
                          multiple
                          type="医嘱字典"
                          :search-params="{ blcybh: cItem.searchKey }"
                          :input-or-textarea="true"
                          :disabled="formState.isCommit === 1"
                          allow-clear
                          placeholder="备注"
                        />
                        <!-- <a-input v-model:value="formData[cItem.memoOS]" :disabled="formState.isCommit === 1" allow-clear placeholder="备注" /> -->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event, true)"
              @clear="inputChange(item.value, item.code, $event)"
              @blur="inputChange(item.value, item.code, $event)"
            />
            <SelectTags
              v-else-if="item.label === '主诉'"
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              :row-val="4"
              input-class="pr-64"
              show-setting
              show-new
              multiple
              :input-or-textarea="item.textarea ? false : true"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            >
              <template #addonAfter>
                <div class="textarea-with-data-picker flex items-center">
                  发病日期<a-date-picker
                    v-model:value="formState.onsetDate"
                    class="ml-2"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @click="handleChildClick"
                  />
                </div>
              </template>
            </SelectTags>
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :input-or-textarea="item.textarea ? false : true"
              :row-val="4"
              :disabled="formState.isCommit === 1"
              show-setting
              show-new
              multiple
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <!-- 眼科病历三 -->
      <div v-else-if="mrmCode === 'YKBL3'" class="case-table my-2">
        <div v-for="item in EYEItems3" :key="item.value" class="case-item">
          <template v-if="item.label === '处理' || item.label === '处理意见'">
            <div class="label flex justify-between items-center" :class="{ large: item.textarea }">
              <div>{{ item.label }}</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetDispose(1, true)">提取</a-button>
            </div>
          </template>
          <template v-else-if="item.label === '辅助检查'">
            <div class="label flex justify-between items-center" :class="{ large: item.textarea }">
              <div>{{ item.label }}</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetFZCheck()">提取</a-button>
            </div>
          </template>
          <div v-else class="label h-10" :class="{ required: item.label === '初步诊断', large: item.textarea }">{{ item.label }}</div>
          <div class="content">
            <div v-if="item.label === '初步诊断'" class="flex h-[54px]">
              <SelectTable
                v-model:value="formState[item.value]"
                type="诊断"
                :custom-input="diagnosisCode"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                @clear="onClear"
                @select="onSelect(item.value, item.code, $event)"
                @input-change="onInputChange(item.code)"
              />
              <a-radio-group v-model:value="formState.bcYblb" :disabled="formState.isCommit === 1" class="flex items-center" name="radioGroup">
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
            </div>
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
              @select="onSelect(item.value, item.code, $event, true)"
              @clear="inputChange(item.value, item.code, $event)"
              @blur="inputChange(item.value, item.code, $event)"
            />
            <SelectTags
              v-else-if="item.label === '主诉'"
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              :row-val="item.textarea ? 4 : 2"
              input-class="pr-64"
              show-setting
              show-new
              multiple
              :input-or-textarea="false"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            >
              <template #addonAfter>
                <div class="textarea-with-data-picker flex items-center">
                  发病日期<a-date-picker
                    v-model:value="formState.onsetDate"
                    class="ml-2"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    @click="handleChildClick"
                  />
                </div>
              </template>
            </SelectTags>
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit === 1"
              :row-val="item.textarea ? 4 : 2"
              show-setting
              show-new
              multiple
              :input-or-textarea="false"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <div class="flex justify-end mt-4 sticky bottom-0 p-4 bg-white">
        <a-button class="mr-4" @click="onReset">重置</a-button>
        <a-button class="mr-4" :disabled="formState.isCommit === 1" type="primary" @click="onSubmit()">保存</a-button>
        <a-button v-if="formState.isCommit !== 1" type="primary" :disabled="!formState.bcLczdZddm" @click="onSubmit('1', false)">提交</a-button>
        <a-button v-else type="primary" @click="onSubmit('0', false)">撤销</a-button>
      </div>
      <TemplateModal v-model:open="templateModalOpen" :mrm-code="mrmCode" @success="onTempSuccess" />
    </a-form>
  </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import SelectTags from '@/components/SelectTags'
import SelectTable from '@/components/SelectTable'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '../../store'
import InspectionTable from '../components/InspectionTable'
import TemplateModal from './TemplateModal'
import SelectOptions from './SelectOptions.vue'
import PrintView from './PrintView'

const { empId } = useUserStore()
const props = defineProps({
  caseData: {
    type: Object,
    default: () => ({})
  },
  activeKey: {
    type: String,
    default: ''
  }
})
const setbh = getSystemConfig('ORGNIZATION_CODE') //组织机构代码
const host = getSystemConfig('HIS_MEDICAL_RECORD_URL') //跳转病历系统地址
const diagnosisCode = getSystemConfig('OUTP_ALLOW_INPUT_ICD10') === '1' // 门诊允许输入诊断 0不允许，1允许
const emit = defineEmits(['success'])
const store = useStore()
const inspectData = ref({})
const formState = ref({ bcYblb: 'OU' })
const formData = ref({})
const templateModalOpen = ref(false)
const isPrintStatus = ref()
const printType = ref()
const inspectShow = ref(true)
const WMItems = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '体格检查', value: 'bcTgjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '注意事项', value: 'bcZysx' },
  { label: '处置', value: 'bcCz' }
])
const TCMItems = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '舌质', value: 'zybcSz' },
  { label: '舌苔', value: 'zybcSt' },
  { label: '脉象', value: 'zybcMx' },
  { label: '阳性体征', value: 'zybcYxtz' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '体格检查', value: 'bcTgjc' },
  { label: '辩证施治', value: 'zybcBzsz' },
  { label: '西医诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '中医诊断', value: 'zybcZyzdZdmc', code: 'zybcZyzdZddm' },
  { label: '中医证名', value: 'zybcZyzxMc', code: 'zybcZyzxDm' },
  // { label: '其他诊断', value: 'bcQtzd' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理意见', value: 'bcClyj' },
  { label: '医嘱建议', value: 'bcYzjy' }
])
const EYEItems1 = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '现病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '个人史', value: 'bcGrs' },
  { label: '家族史', value: 'bcJzs' },
  { label: '过敏史', value: 'bcGms' },
  { label: '眼部检查', value: 'bcYbjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理意见', value: 'bcCl', textarea: true }
  // { label: '交待', value: 'bcJd', textarea: true }
])
const EYEItems3 = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '现病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  // { label: '个人史', value: 'bcGrs' },
  { label: '家族史', value: 'bcJzs' },
  { label: '过敏史', value: 'bcGms' },
  { label: '眼部检查', value: 'bcYbjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理', value: 'bcCl', textarea: true },
  { label: '交待', value: 'bcJd', textarea: true }
])
const EYEItems2 = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '现病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '过敏史', value: 'bcGms' },
  // { label: '家族史', value: 'bcJzs' },
  { label: '眼部检查', value: 'bcYbjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理意见', value: 'bcCl', textarea: true }
  // { label: '交待', value: 'bcJd', textarea: true }
])
const EYEChildItems = ref([
  { label: '眼别', value: 'bcZs' },
  {
    label: '眼睑（睑缘）',
    key: '睑缘',
    searchKey: '眼睑（睑缘）',
    mode: 'combobox',
    valueOS: 'jy_os',
    valueOD: 'jy_od',
    memoOS: 'yl_bz_os',
    memoOD: 'yl_bz_od'
  },
  {
    label: '眼睑（睑板腺开口）',
    key: '睑板腺开口',
    searchKey: '眼睑（睑板腺开口）',
    mode: 'combobox',
    valueOS: 'jbxkk_os',
    valueOD: 'jbxkk_od',
    memoOS: 'ybxkk_bz_os',
    memoOD: 'ybxkk_bz_od'
  },
  { label: '泪器', key: '泪器', searchKey: '泪器', mode: 'combobox', valueOS: 'lq_os', valueOD: 'lq_od', memoOS: 'lq_bz_os', memoOD: 'lq_bz_od' },
  { label: '结膜', key: '结膜', searchKey: '结膜', mode: 'combobox', valueOS: 'jm_os', valueOD: 'jm_od', memoOS: 'jm_bz_os', memoOD: 'jm_bz_od' },
  { label: '角膜', key: '角膜', searchKey: '角膜', mode: 'combobox', valueOS: 'jmo_os', valueOD: 'jmo_od', memoOS: 'jmo_bz_os', memoOD: 'jmo_bz_od' },
  { label: '前房', key: '前房', searchKey: '前房', mode: 'combobox', valueOS: 'qf_os', valueOD: 'qf_od', memoOS: 'qf_bz_os', memoOD: 'qf_bz_od' },
  { label: '虹膜', key: '虹膜', searchKey: '虹膜', mode: 'combobox', valueOS: 'hm_os', valueOD: 'hm_od', memoOS: 'hm_qt_os', memoOD: 'hm_qt_od' },
  { label: '瞳孔', key: '瞳孔形态', searchKey: '瞳孔', mode: 'combobox', valueOS: 'tk_xt_os', valueOD: 'tk_xt_od', memoOS: 'tk_bz_os', memoOD: 'tk_bz_od' },
  { label: '晶状体', key: '晶状体', searchKey: '', mode: 'combobox', valueOS: 'jzt_os', valueOD: 'jzt_od', memoOS: '', memoOD: '' },
  {
    label: '晶状体（位置）',
    key: '晶状体位置',
    searchKey: '晶状体',
    mode: 'combobox',
    valueOS: 'jzt_os_wz',
    valueOD: 'jzt_od_wz',
    memoOS: 'jzt_bz_os',
    memoOD: 'jzt_bz_od'
  },
  {
    label: '眼底（玻璃体）',
    key: '玻璃体',
    searchKey: '眼底(玻璃体)',
    mode: 'combobox',
    valueOS: 'blt_os',
    valueOD: 'blt_od',
    memoOS: 'blt_bz_os',
    memoOD: 'blt_bz_od'
  },
  {
    label: '眼底（视网膜）',
    key: '视网膜',
    searchKey: '眼底(视网膜)',
    mode: 'combobox',
    valueOS: 'yd_swm_os',
    valueOD: 'yd_swm_od',
    memoOS: 'yd_swmbz_os',
    memoOD: 'yd_swmbz_od'
  },
  {
    label: '眼底（黄斑中心凹反光）',
    key: '黄斑中心凹反光',
    searchKey: '眼底(黄斑中心凹反光)',
    mode: 'combobox',
    valueOS: 'yd_hbzxafg_os',
    valueOD: 'yd_hbzxafg_od',
    memoOS: 'yd_hbzxafgbz_os',
    memoOD: 'yd_hbzxafgbz_od'
  },
  { label: '眼底（视盘/CD）', key: '眼底视盘', searchKey: '', mode: 'combobox', valueOS: 'yd_cd_os', valueOD: 'yd_cd_od', memoOS: '', memoOD: '' },
  { label: '其他（专科检查）', key: '其他检查', searchKey: '', mode: 'tags', valueOS: 'qtzkjc_os', valueOD: 'qtzkjc_od', memoOS: '', memoOD: '' },
  { label: '备注', key: '备注', searchKey: '', mode: '', valueOS: '', valueOD: '', memoOS: '', memoOD: 'qtfzjc_od' }
])
//获取处置
const onGetDispose = async (state, status) => {
  if (!store.currentPatient.jzbh) return
  const res = await post('/outp/mzys/lnkAutoZlclLinkClicked', {
    jzbh: store.currentPatient.jzbh,
    sfykbl: status ? state : undefined
  })
  if (res.code !== 0) return message.error(res.msg)
  if (state === 1) {
    const dataText = res.data.includes(formState.value.bcCl) ? res.data : formState.value.bcCl
    formState.value.bcCl = dataText || res.data
  } else {
    const dataText = res.data.includes(formState.value.bcCz) ? res.data : formState.value.bcCz
    formState.value.bcCz = dataText || res.data
  }
  // state === 1 && (formState.value.bcCl = res.data || '')
  // state === 2 && (formState.value.bcCz = res.data || '')
}
//获取辅助检查
const onGetFZCheck = async () => {
  if (!store.currentPatient.jzbh) return
  const res = await post('/outp/mzys/lnkAutoExamineLink', {
    jzbh: store.currentPatient.jzbh,
    sfykbl: ''
  })
  if (res.code !== 0) return message.error(res.msg)
  const dataText = res.data.includes(formState.value.bcFzjc) ? res.data : formState.value.bcFzjc
  formState.value.bcFzjc = dataText || res.data
}

//获取病历类型
// const caseTypeOptions = ref([])
const mrmCode = ref('')
// const getCaseType = async () => {
//   const res = await post('/common/const/getMedicalRecordMode', { mrmType: 0 })
//   caseTypeOptions.value = res.data || []
//   // mrmCode.value = res.data?.[0]?.mrmCode
// }
const timer = ref(null)
// 获取当前医生默认显示的病历
const getMedical = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId })
  if (res.code !== 0) return message.error(res.msg)

  mrmCode.value = res.data && res.data.blmb
  if (mrmCode.value === 'YKBL4') {
    formatFourBl()
    mrmCode.value = 'YKBL3'
  }
  if (mrmCode.value === 'YKBL2') getEyeData()
  if (mrmCode.value === 'YKBL2' || mrmCode.value === 'YKBL3') {
    getInspectData()
    onGetDispose(1, true)
    inspectShow.value = true
    timer.value = setTimeout(() => {
      inspectShow.value = getSystemConfig('OUTP_OO_GENERAL_INSEPECION_SHOW_MODE') === '0'
    }, 3000)
  }
  if (mrmCode.value === 'XYBL') {
    onGetDispose(2, false)
  }
}
const formatFourBl = () => {
  EYEItems3.value = [
    { label: '主诉', value: 'bcZs' },
    { label: '现病史', value: 'bcXbs' },
    { label: '既往史', value: 'bcJws' },
    // { label: '个人史', value: 'bcGrs' },
    { label: '家族史', value: 'bcJzs' },
    { label: '过敏史', value: 'bcGms' },
    { label: '眼部检查', value: 'bcYbjc' },
    { label: '辅助检查', value: 'bcFzjc' },
    { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
    { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
    { label: '处理意见', value: 'bcCl', textarea: true }
  ]
}
const tranInspect = (val) => {
  inspectShow.value = val
}

//保存病历信息
const onSubmit = async (status, state = true) => {
  if (mrmCode.value === 'ZYBL') {
    if (!formState.value.zybcZyzdZddm) return message.error('请选择中医诊断')
    if (!formState.value.zybcZyzxDm) return message.error('请选择中医证名')
  }
  if (mrmCode.value.indexOf('YKBL') > -1) {
    if (!formState.value.bcYblb) return message.error('请选择眼别')
  }
  if (store.currentPatient.tabStatus !== '手术') {
    const isCheck = await checkPatientStatus(store.currentPatient.jzbh)
    if (!isCheck) return
  }
  const params = {
    ...formState.value,
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh,
    mrmCode: mrmCode.value,
    medicalRecordStyle: mrmCode.value,
    signPaperwork: formState.value?.signPaperwork ? 1 : 0,
    qtzdxx: '',
    isCxtj: status ?? undefined,
    isCommit: status ?? undefined
  }
  // 如果允许输入，要判断用户是选中的还是输入的 bcLczdZddm
  if (diagnosisCode) {
    if (!params?.bcLczdZddm && params?.bcLczdZdmc) {
      params.bcLczdZddm = 'ICD10_INPUT'
    }
  }
  const res = await post('outp/mzys/doSavePatientEMR', params)
  if (res.code !== 0) return message.error(res.msg)
  //如果是眼科病历二
  if (mrmCode.value === 'YKBL2' || mrmCode.value === 'YKBL3') {
    const form = { ...formData.value }
    EYEChildItems.value.forEach((item) => {
      if (item.key !== '其他检查') return
      if (form[item.valueOS] && form[item.valueOS].length > 0) {
        form[item.valueOS] = form[item.valueOS].join(',')
      }
      if (form[item.valueOD] && form[item.valueOD].length > 0) {
        form[item.valueOD] = form[item.valueOD].join(',')
      }
    })
    Object.keys(form).forEach((key) => {
      if (!form[key]) form[key] = ''
    })
    const saveForm = {
      ...form,
      brId: store.currentPatient.brId,
      jzbh: store.currentPatient.jzbh,
      setbh: form.setbh ? form.setbh : setbh
    }
    // const res1 = await post('/OPTOMETY/SaveZKJC', {
    const res1 = await post('/outp/mzys/SaveZKJC', saveForm)
    if (res1.code !== 0) return message.error(res1.msg)
    if (state) {
      message.success('保存成功')
    } else {
      message.success(status === '1' ? '提交成功' : '撤销成功')
    }
  } else {
    if (state) {
      message.success('保存成功')
    } else {
      message.success(status === '1' ? '提交成功' : '撤销成功')
    }
  }
  if (mrmCode.value === 'YKBL2') {
    setTimeout(() => {
      getEyeData()
    }, 1000)
  }
  emit('success')
}
const onTempSuccess = (data) => {
  formState.value = data
}

// 重置
const onReset = () => {
  for (const key in formState.value) {
    if (Object.hasOwnProperty.call(formState.value, key)) {
      formState.value[key] = ''
    }
  }
  formState.value.isCommit = false
}

//获取常规检查
const getInspectData = async () => {
  if (!store.currentPatient.jzbh) return
  const { code, data, msg } = await post('/outp/mzys/getCGJCInfo', { jzbh: store.currentPatient.jzbh, setbh: setbh })
  // const { code, data, msg } = await post('OPTOMETY/getCGJCInfo', { jzbh: store.currentPatient.jzbh, setbh: setbh })
  if (code !== 0) return message.error(msg)

  inspectData.value = data ? JSON.parse(data) : {}
  if (inspectData.value.listBLJLB_YG && inspectData.value.listBLJLB_YG.length > 0) {
    const YGArr = inspectData.value.listBLJLB_YG.filter((item) => {
      return item.yglb === '电脑验光'
    })
    if (YGArr && YGArr.length > 0) {
      inspectData.value.listBLJLB_YG_DATA = YGArr[0]
    } else {
      inspectData.value.listBLJLB_YG_DATA = {
        yglb: '电脑验光'
      }
    }
    const YGArr1 = inspectData.value.listBLJLB_YG.filter((item) => {
      return item.yglb === '插片验光'
    })
    if (YGArr1 && YGArr1.length > 0) {
      inspectData.value.listBLJLB_CP_DATA = YGArr1[0]
    } else {
      inspectData.value.listBLJLB_CP_DATA = {
        yglb: '插片验光'
      }
    }
    const YGArr2 = inspectData.value.listBLJLB_YG.filter((item) => {
      return item.yglb === '散瞳验光'
    })
    if (YGArr1 && YGArr1.length > 0) {
      inspectData.value.listBLJLB_ST_DATA = YGArr2[0]
    } else {
      inspectData.value.listBLJLB_ST_DATA = {
        yglb: '散瞳验光'
      }
    }
  } else {
    inspectData.value.listBLJLB_YG_DATA = { yglb: '电脑验光' }
    inspectData.value.listBLJLB_CP_DATA = { yglb: '插片验光' }
    inspectData.value.listBLJLB_ST_DATA = { yglb: '散瞳验光' }
  }
}
// bcLczdZdmc
// 获取眼部检查数据
const getEyeData = async () => {
  if (!store.currentPatient.jzbh) return
  const { code, data, msg } = await post('/outp/mzys/getZKJCInfo', { jzbh: store.currentPatient.jzbh, setbh: setbh })
  // const { code, data, msg } = await post('/OPTOMETY/getZKJCInfo', { jzbh: store.currentPatient.jzbh, setbh: setbh })
  if (code !== 0) return message.error(msg)
  const form = data ? JSON.parse(data) : {}
  EYEChildItems.value.forEach(async (item) => {
    if (item.key === '其他检查') {
      if (form[item.valueOS]) {
        form[item.valueOS] = form[item.valueOS].split(',')
      }
      if (form[item.valueOD] && form[item.valueOD].length > 0) {
        form[item.valueOD] = form[item.valueOD].split(',')
      }
    } else {
      //如果bcLczdZddm有值，说明不是一地刺保存，就不用给眼部检查赋初始值
      if (props.caseData.bcLczdZddm) return
      if (item.label === '眼别' || item.key === '晶状体位置' || item.key === '眼底视盘' || item.key === '备注') return
      if (!form[item.valueOS] || !form[item.valueOD]) {
        // const res = await post('OPTOMETY/getDictList', { pmlb: item.key, setbh: setbh })
        const res = await post('/outp/mzys/getDictList', { pmlb: item.key, setbh: setbh })
        if (res.code === 0 && res.data) {
          if (JSON.parse(res.data).length > 0) {
            if (!form[item.valueOS]) formData.value[item.valueOS] = JSON.parse(res.data)[0].mc
            if (!form[item.valueOD]) formData.value[item.valueOD] = JSON.parse(res.data)[0].mc
          }
        }
      }
    }
  })
  formData.value = form
}

// 获取病史
const onClickHistory = async () => {
  const { code, data, msg } = await post('/outp/mzys/getOutpMedicalHistory', { brId: store.currentPatient.brId })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  data && (formState.value = data)
}

const onClickRead = () => {
  // crmp.fudan-soft.net
  // 10.11.10.201:7217
  window.open(`http://crmp.fudan-soft.net/AJAX/CS_Result?page=famWJSZ&setbh=${setbh}&emp_id=${empId}&br_id=${store.currentPatient.brId}`)
}
const printData = ref()
const printMe = ref()

// 打印病历单
const onPrintMedical = async () => {
  const { code, msg, data } = await post('/outp/outPrint/printrptMZBL', { brId: store.currentPatient.brId, jzbh: store.currentPatient?.jzbh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 打印中医病历
// const onPrintZy = async () => {}
// 打印眼科病历
const onPrintEye = async () => {
  let splicing = ''
  EYEChildItems.value.forEach((item) => {
    // if (index === 0 || item.key === '备注') return
    // 检查是否有数据存在于该项
    let str = ''
    for (const key in formData.value) {
      if (key === item.valueOD) {
        if (formData.value[item.valueOD] || formData.value[item.memoOD]) {
          str += `右眼${formData.value[item.valueOD] ? formData.value[item.valueOD] : ''}`
          str += `${formData.value[item.memoOD] ? ',' + formData.value[item.memoOD] + ';' : ';'}`
        }
      }
      if (key === item.valueOS) {
        if (formData.value[item.valueOS] || formData.value[item.memoOS]) {
          str += `左眼${formData.value[item.valueOS] ? formData.value[item.valueOS] : ''}`
          str += `${formData.value[item.memoOS] ? ',' + formData.value[item.memoOS] + '。' : '。'}`
        }
      }
      if (key === item.memoOD && item.memoOD === 'qtfzjc_od') {
        if (formData.value[key]) {
          str += `${formData.value['qtfzjc_os'] ? formData.value[key] + ';' : formData.value[key] + '。'}`
        }
      }
      // if (key === item.memoOS && item.memoOS === 'qtfzjc_os') {
      //   if (formData.value[key]) {
      //     str += `左眼${formData.value[key] + '。'}`
      //   }
      // }
    }
    // 只有当有数据时才进行拼接
    if (str) {
      splicing += item.label + ':' + str
    }
  })
  const strUrl = mrmCode.value === 'YKBL2' ? '/outp/outPrint/printrptPhthalmic2MedicalRecords' : '/outp/outPrint/printrptQDFBOphthalmicMedicalRecords'
  const { code, msg, data } = await post(strUrl, {
    ysl_ly_od: inspectData.value.mBLJLB_SL?.lysl_y_od || '-', // 远视力（裸眼） od
    ysl_ly_os: inspectData.value.mBLJLB_SL?.lysl_y_os || '-', // 远视力（裸眼） os
    jsl_ly_od: inspectData.value.mBLJLB_SL?.lysl_j_od || '-', // 近视力（裸眼） od
    jsl_ly_os: inspectData.value.mBLJLB_SL?.lysl_j_os || '-', // 近视力（裸眼） os
    ysl_jz_od: inspectData.value.mBLJLB_SL?.jzsl_y_od || '-', // 远视力（矫正） od
    ysl_jz_os: inspectData.value.mBLJLB_SL?.jzsl_y_os || '-', // 远视力（矫正） os
    jsl_jz_od: inspectData.value.mBLJLB_SL?.jzsl_j_od || '-', // 近视力（矫正） od
    jsl_jz_os: inspectData.value.mBLJLB_SL?.jzsl_j_os || '-', // 近视力（矫正） os
    yy_od: judgeVal(inspectData.value.mBLJLB_YY?.yy_od) || '-', //眼压od
    yy_os: judgeVal(inspectData.value.mBLJLB_YY?.yy_os) || '-', //眼压os
    dnyg_od: onOptometryOd(inspectData.value.listBLJLB_YG_DATA) || '-',
    dnyg_os: onOptometryOs(inspectData.value.listBLJLB_YG_DATA) || '-',
    jmql_od: onCorneaOd(inspectData.value.mBLJLB_YBJC) || '-',
    jmql_os: onCorneaOs(inspectData.value.mBLJLB_YBJC) || '-',
    cpyg_od: onInsertsOd(inspectData.value.listBLJLB_CP_DATA) || '-',
    cpyg_os: onInsertsOs(inspectData.value.listBLJLB_CP_DATA) || '-',
    styg_od: onMydriasisOd(inspectData.value.listBLJLB_ST_DATA) || '-',
    styg_os: onMydriasisOs(inspectData.value.listBLJLB_ST_DATA) || '-',
    // bz_od: inspectData.value.listBLJLB_YG_DATA.cmemo_od, //备注 od
    // bz_os: inspectData.value.listBLJLB_YG_DATA.cmemo_os, //备注 os
    zkjc: splicing,
    jzbh: store.currentPatient?.jzbh,
    qtfzjc_os: formData.value['qtfzjc_os'] || '-',
    qtfzjc_od: formData.value['qtfzjc_od'] || '-'
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 电脑验光od
const onOptometryOd = (params) => {
  let result = ''
  if (judgeVal(params?.sph_od) !== '') {
    result += judgeVal(params?.sph_od) + ' DS '
  }
  if (judgeVal(params?.cyl_od) !== '') {
    result += judgeVal(params?.cyl_od) + ' DCX '
  }
  if (judgeVal(params?.axis_od) !== '') {
    result += judgeVal(params?.axis_od) + '°'
  }
  return result.trim() // 移除末尾的空格
}
// 电脑验光os
const onOptometryOs = (params) => {
  let result = ''
  if (judgeVal(params?.sph_os) !== '') {
    result += judgeVal(params?.sph_os) + ' DS '
  }
  if (judgeVal(params?.cyl_os) !== '') {
    result += judgeVal(params?.cyl_os) + ' DCX '
  }
  if (judgeVal(params?.axis_os) !== '') {
    result += judgeVal(params?.axis_os) + '°'
  }
  return result.trim() // 移除末尾的空格
}
// 角膜曲率od
const onCorneaOd = (params) => {
  let result = ''
  if (judgeVal(params?.jmql_hk_od) !== '') {
    result += judgeVal(params?.jmql_hk_od) + '  @/'
  }
  if (judgeVal(params?.jmql_vk_od) !== '') {
    result += judgeVal(params?.jmql_vk_od) + '  @'
  }
  if (judgeVal(params?.jmql_e_od) !== '') {
    result += judgeVal(params?.jmql_e_od)
  }
  return result.trim() // 移除末尾的空格
}
// 角膜曲率os
const onCorneaOs = (params) => {
  let result = ''
  if (judgeVal(params?.jmql_hk_os) !== '') {
    result += judgeVal(params?.jmql_hk_os) + '  @/'
  }
  if (judgeVal(params?.jmql_vk_os) !== '') {
    result += judgeVal(params?.jmql_vk_os) + '  @'
  }
  if (judgeVal(params?.jmql_e_os) !== '') {
    result += judgeVal(params?.jmql_e_os)
  }
  return result.trim() // 移除末尾的空格
}

// 插片验光Od
const onInsertsOd = (params) => {
  let result = ''
  if (judgeVal(params?.sph_od) !== '') {
    result += judgeVal(params?.sph_od) + ' DS  '
  }
  if (judgeVal(params?.cyl_od) !== '') {
    result += judgeVal(params?.cyl_od) + ' DCX '
  }
  if (judgeVal(params?.axis_od) !== '') {
    result += judgeVal(params?.axis_od) + '°'
  }
  if (judgeVal(params?.va_od) !== '') {
    result += '插片后视力' + judgeVal(params?.va_od)
  }
  return result.trim() // 移除末尾的空格
}
// 插片验光Os
const onInsertsOs = (params) => {
  let result = ''
  if (judgeVal(params?.sph_os) !== '') {
    result += judgeVal(params?.sph_os) + ' DS  '
  }
  if (judgeVal(params?.cyl_os) !== '') {
    result += judgeVal(params?.cyl_os) + ' DCX '
  }
  if (judgeVal(params?.axis_os) !== '') {
    result += judgeVal(params?.axis_os) + '°'
  }
  if (judgeVal(params?.va_os) !== '') {
    result += '插片后视力' + judgeVal(params?.va_os)
  }
  return result.trim() // 移除末尾的空格
}

// 散瞳验光od
const onMydriasisOd = (params) => {
  let result = ''
  if (judgeVal(params?.sph_od) !== '') {
    result += judgeVal(params?.sph_od) + ' DS  '
  }
  if (judgeVal(params?.cyl_od) !== '') {
    result += judgeVal(params?.cyl_od) + ' DCX '
  }
  if (judgeVal(params?.axis_od) !== '') {
    result += judgeVal(params?.axis_od) + '°'
  }
  if (judgeVal(params?.va_od) !== '') {
    result += '散瞳后视力' + judgeVal(params?.va_od)
  }
  return result.trim() // 移除末尾的空格
}

// 散瞳验光od
const onMydriasisOs = (params) => {
  let result = ''
  if (judgeVal(params?.sph_os) !== '') {
    result += judgeVal(params?.sph_os) + ' DS  '
  }
  if (judgeVal(params?.cyl_os) !== '') {
    result += judgeVal(params?.cyl_os) + ' DCX '
  }
  if (judgeVal(params?.axis_os) !== '') {
    result += judgeVal(params?.axis_os) + '°'
  }
  if (judgeVal(params?.va_os) !== '') {
    result += '散瞳后视力' + judgeVal(params?.va_os)
  }
  return result.trim() // 移除末尾的空格
}

// 打印病程单
const onPrint = async () => {
  if (mrmCode.value === 'XYBL') {
    printType.value = 0
  } else if (mrmCode.value === 'ZYBL') {
    printType.value = 1
  } else {
    printType.value = 2
  }

  if (isPrintStatus.value === '0' || isPrintStatus.value === '2') {
    const { code, msg, data } = await post('/outp/outPrint/getMZBCD', {
      mzjlbh: store.currentPatient.jzbh,
      pjhm: store.currentPatient.pjhm,
      type: printType.value
    })
    if (code !== 0) return message.error(msg)
    if (isArmy) {
      printData.value = JSON.parse(data)
      setTimeout(() => {
        printMe.value.$el.click()
      }, 1000)
    } else {
      window.openExe?.rpt(data) //调用winform打印
    }
  } else if (isPrintStatus.value === '1') {
    // window.open(`/api/v1/outp/outPrint/printTreatmentSheet?jzbh= ${store.currentPatient.jzbh} `)
    window.open(`${host}/Ajax/CS_Result?page=rptMZXBL_JG&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`)
  }
}

// 合并打印
const onPrintS = () => {
  onPrintMedical()
  onPrint()
}

watch(
  () => store.tempCase,
  () => {
    formState.value = store.tempCase
  }
)
const inputChange = (value, code, event) => {
  if (!event) {
    formState.value[code] = ''
  } else {
    if (!formState.value[value]) return
    if (formState.value[value].split('，').length !== formState.value[code].split('，').length) {
      formState.value[code] = formState.value[code].split('，').slice(0, formState.value[value].split('，').length).join('，')
    }
  }
}
// 眼部检查/其他检查
const onSelectPageTwo = (value, code, select, multiple = false) => {
  if (multiple) {
    //多选拼接
    formState.value[value] = formState.value[value] ? formState.value[value] + '，' + select.zdmc || select.mc : select.zdmc || select.mc
  } else {
    formState.value[value] = select.zdmc || select.mc
    formState.value[code] = select.zddm || select.dm
  }
}
const onSelect = (value, code, select, multiple = false) => {
  if (multiple) {
    //多选拼接
    formState.value[value] = formState.value[value] ? formState.value[value] + '，' + select.zdmc || select.mc : select.zdmc || select.mc
    formState.value[code] = formState.value[code] ? formState.value[code] + '，' + select.zddm || select.dm : select.zddm || select.dm
    if (formState.value[value].split('，').length !== formState.value[code].split('，').length) {
      const str = formState.value[value].split('，')
      str.splice(formState.value[value].split('，').length - 2, 1)
      formState.value[value] = str.join('，')
    }
  } else {
    formState.value[value] = select.zdmc || select.mc
    formState.value[code] = select.zddm || select.dm
    // formState.value[code + 'YB'] = select.nmiIcd10Code
    // formState.value[value + 'YB'] = select.nmiIcd10Name
  }
}
const onInputChange = (code) => {
  formState.value[code] = ''
}
const onClear = () => {
  if (formState.value.bcLczdZdmc) {
    if (!formState.value.bcLczdZddm) {
      formState.value.bcLczdZddm = 'ICD10_INPUT'
    }
  } else {
    formState.value.bcLczdZddm = ''
  }
  // if (formState.value.bcLczdZdmc && formState.value.bcLczdZddm !== 'ICD10_INPUT') {
  //   formState.value.bcLczdZddm = ''
  // } else {
  //   if (formState.value.bcLczdZdmc) {
  //     formState.value.bcLczdZddm = 'ICD10_INPUT'
  //   } else {
  //     formState.value.bcLczdZddm = ''
  //   }
  // }
}
const handleChildClick = (event) => {
  event.stopPropagation() // 阻止事件冒泡
}

watch(
  () => store.currentPatient.jzbh,
  async () => {
    // getCaseType()
    await getMedical()
    // getEyeData()
    // getInspectData()
  }
)

watch(
  () => props.activeKey,
  async (val) => {
    if (val === '1') {
      formState.value = { ...props.caseData }
      if (!formState.value.bcLczdZddm) formState.value.onsetDate = dayjs().format('YYYY-MM-DD')
      formState.value.signPaperwork = formState.value.signPaperwork ? true : false
      // getCaseType()
      await getMedical()
      // getEyeData()
      // getInspectData()
    }
  },
  {
    immediate: true
  }
)

watch(
  () => props.caseData,
  (value) => {
    formState.value = { ...value }
    if (!formState.value.bcLczdZddm) formState.value.onsetDate = dayjs().format('YYYY-MM-DD')
    formState.value.signPaperwork = formState.value.signPaperwork ? true : false
    store.currentMedical = formState.value
    // if (mrmCode.value === 'YKBL2' || mrmCode.value === 'YKBL3') {
    //   onGetDispose(1, true)
    // }
    // if (mrmCode.value === 'XYBL') {
    //   onGetDispose(2, false)
    // }
  },
  { deep: true, immediate: true }
)

// const yqbh = getSystemConfig('OUTP_OPHTH_INSTRUMENT_BH') //仪器编号
// const getPACSUrl = (view, isYqflg = false, isYqbh = false) => {
//   let url = `${host}/Ajax/CS_Result?page=${view}&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`
//   isYqflg && (url += `&yqflg=1`)
//   isYqbh && (url += `&yqbh=${yqbh}`)
//   return url
// }

// const setIframeHeight = (height = 0) => {
//   const iframe = document.getElementById('dlgCGJC')
//   if (iframe) {
//     iframe.height = `${height}px`
//   }
// }
const judgeVal = (val) => {
  if (val || val === '0' || val === 0) {
    return val
  } else {
    return ''
  }
}
// window.addEventListener('message', (event) => {
//   event.data === 'reloadHisTab' && getDynamicUrl()
//   event.data.bodyHeight && setIframeHeight(event.data.bodyHeight)
// })
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统

onMounted(() => {
  // getDynamicUrl()
  isPrintStatus.value = getSystemConfig('OUTP_MEDICAL_DOCUMENT_PRINT_MODE') // 0：通用|1：上海黑马|2：茗视光
  // printTitle.value = isPrintStatus.value === '1' ? '打印病历小票' : '打印病程单'
})
onUnmounted(() => {
  clearTimeout(timer.value)
  timer.value = null
})
</script>
<style lang="less" scoped>
.case-table {
  --border-color: rgba(125, 125, 125, 0.3);
  border: 1px solid var(--border-color);

  .case-item {
    display: flex;

    .required {
      position: relative;

      &::before {
        position: absolute;
        top: 8px;
        left: 8px;
        color: red;
        content: '*';
      }
    }

    .label.large {
      align-items: start;
      height: auto;
    }

    .label {
      display: flex;
      align-items: center;
      width: 278px;
      height: 54px;
      padding: 8px 16px;
      background-color: #eeeeee;

      border-right: 1px solid var(--border-color);
      border-bottom: 1px solid var(--border-color);
    }

    .label-eye {
      display: flex;
      align-items: center;
      width: 278px;
      background-color: #eeeeee;
      border-right: 1px solid var(--border-color);
      border-bottom: 1px solid var(--border-color);

      .eye-border-left {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 94px;

        .eye-border-left-con {
          padding: 8px 16px;
        }
      }

      .eye-border-right {
        width: 184px;
        border-left: 1px solid var(--border-color);

        .eye-border-right-con {
          padding: 8px 10px 8px 16px;
          border-bottom: 1px solid var(--border-color);
        }

        .eye-border-right-con:last-child {
          border-bottom: none;
        }
      }
    }

    .content {
      flex: 1;
      overflow: hidden;
      border-bottom: 1px solid var(--border-color);

      :deep(.ant-input) {
        height: 100%;
        border: none;
        border: 1px solid transparent;
        border-radius: 0;

        &:focus {
          background: var(--edit-cell-color);
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }

        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
      }

      :deep(.ant-select) {
        height: 100%;
        padding-top: 3px;
        border: 1px solid transparent;
        border-radius: 0;

        &:focus {
          background: var(--edit-cell-color);
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }

        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
      }

      :deep(.ant-input-affix-wrapper) {
        height: 100%;
        background: var(--bg-color);
        border: 1px solid transparent;
        border-radius: 0;

        &-focused {
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }

        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }

        .ant-input {
          border: none;
        }
      }

      .eye-box {
        background-color: #eeeeee;

        .eye-box-header-left {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          border-right: 1px solid var(--border-color);
          border-bottom: 1px solid var(--border-color);
        }

        .eye-box-header-right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          border-bottom: 1px solid var(--border-color);
        }
      }

      .eye-item-box {
        border-bottom: 1px solid var(--border-color);

        .eye-box-left {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          height: 100%;
          border-right: 1px solid var(--border-color);

          .eye-box-left-br {
            border-right: 1px solid var(--border-color);
          }
        }

        .eye-box-right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          height: 100%;

          .eye-box-right-br {
            border-right: 1px solid var(--border-color);
          }
        }
      }

      .eye-wrap:last-child {
        .eye-item-box {
          border-bottom: none;
        }
      }
    }

    &:last-child {
      .content,
      .label {
        align-items: flex-start;
        border-bottom: none;
      }
    }

    .content-border-none {
      border-bottom: none !important;
    }
  }
}

.no-data {
  display: flex;
  align-items: center;
  height: 100%;
  padding-left: 12px;
}

.input-bt {
  border-bottom: 1px solid var(--border-color);
}

.textarea-with-data-picker {
  position: absolute;
  top: 50%; /* 将子元素的顶部定位到父元素的 50% 位置 */
  right: 10px;
  z-index: 99;
  width: 240px;
  transform: translateY(-50%); /* 向上移动子元素自身高度的 50% */
}
</style>
